const {Comment, User, House, Reply, Area,School} = require('../db/model/index')

const getCommentList = async ({pageIndex, pageSize}) => {
  const result = await Comment.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    include: [
      {
        model: User,
        attributes: [ 'nickName' ]
      },
      {
        model: House,
        attributes: [ 'name' ]
      }
    ]
  })

  return {
    count: result.count,
    data: result.rows
  }
}

const getCommentOne = async (id) => {
  const result = await Comment.findOne({
    where: {
      id
    },
    include: [
      {
        model: User,
        attributes: [ 'nickName' ]
      },
      {
        model: House,
        include: [
          {
            model: Area,
            attributes: [ 'name' ]
          },
          {
            model: School,
            attributes: [ 'name' ]
          }
        ]
      },
      {
        model: Reply,
        include: [
          {
            model: User,
            attributes: [ 'nickName' ]
          }
        ]
      }
    ]
  })

  return result.dataValues
}

const createComment = async ({title, content, imgs, uid, houseId}) => {
  const result = await Comment.create({
    title,
    content,
    imgs,
    uid,
    houseId
  })

  const data = result.dataValues

  return data
}

const updateComment = async ({title, content, imgs, id}) => {
  const whereOpt = {
    id
  }
  const result = await Comment.update({
    title,
    content,
    imgs
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

const delComment = async (id) => {
  const result = await Comment.destroy({
    where: {
      id
    }
  })

  return result > 0
}

module.exports = {
  getCommentList,
  getCommentOne,
  createComment,
  updateComment,
  delComment
}
